<?php
declare (strict_types = 1);

namespace app\admin\model;

use app\common\model\Rabc\AdminInfos;
use app\common\model\Rabc\AdminWithRoles;
use think\db\exception\PDOException;
use think\facade\Db;

/**
 * @mixin \think\Model
 */
class Admins extends \app\common\model\Rabc\Admins
{
    /**
     * 密码设置
     *
     * @param $value
     *
     * @return string
     */
    public function setPasswordAttr($value)
    {
        if ( !empty($value) ) return hash_encryption($value);
        else return $value;
    }

    public function add(array $params = [])
    {
        Db::startTrans();
        try {
            $admin = $this->create($this->setFilterFields($params));
            // 管理员基本信息
            $client_info = get_client_info();
            AdminInfos::getInstance()->add([$this->pk => $admin->admin_id,
                                         'created_ip' => $client_info['ip'],
                                         'browser_type' => $client_info['agent']]);
            // 管理员关联角色
            $this->setAdminRoles($admin->admin_id, $params);

            $this->setError('插入成功!');
            Db::commit();
            return true;
        } catch (PDOException $e) {
            $this->setError($e->getMessage());
            Db::rollback();
            return false;
        }
    }

    public function edit(array $params = [], array $where = [])
    {
        Db::startTrans();
        try {
            $admin_id = intval($params[$this->pk]);
            // 管理员基本信息
            $this->where($this->pk, $admin_id)->update($this->setFilterFields($params));
            // 管理员关联角色
            $this->setAdminRoles($admin_id, $params);

            $this->setError('更新成功!');
            Db::commit();
            return true;
        } catch (PDOException $e) {
            $this->setError($e->getMessage());
            Db::rollback();
            return false;
        }
    }

    /**
     * 设置关联角色
     *
     * @param $admin
     * @param $params
     *
     * @return bool
     */
    private function setAdminRoles(int $admin_id ,array $params)
    {
        // 删除所有的关联
        AdminWithRoles::where('admin_id', $admin_id)->whereNotIn('role_id', [$params['role_id'] ?? 0])->delete();

        if (
            isset($params['role_id'])
            &&
            !AdminWithRoles::where([
                'admin_id' => $admin_id,
                'role_id' => $params['role_id']
            ])->find()
        ){
            // 新增关联
            AdminWithRoles::create([
                'admin_id' => $admin_id,
                'role_id' => $params['role_id'],
            ]);
        }
    }
}
